package com.jy.oms.framework.asyn.task.core;

import cn.hutool.system.SystemUtil;
import com.jy.oms.framework.asyn.job.IStandaloneJob;
import com.jy.oms.framework.asyn.job.StandaloneJobConfig;
import com.jy.oms.framework.asyn.task.checker.TaskExecutorChainChecker;
import com.jy.oms.framework.asyn.task.cluster.registry.IRegistryService;
import com.jy.oms.framework.asyn.task.constants.CacheConstants;
import com.jy.oms.framework.asyn.task.exception.TaskConfigException;
import com.jy.oms.framework.asyn.task.executor.ITaskController;
import com.jy.oms.framework.asyn.task.handler.ITaskHandlerManager;
import com.jy.oms.framework.asyn.task.handler.ITaskHandlerProcessor;
import com.jy.oms.framework.asyn.task.model.TaskGroup;
import com.jy.oms.framework.asyn.task.model.TaskHandlerWrapper;
import com.jy.oms.framework.asyn.task.util.ServerConfigAdapter;
import com.jy.oms.framework.init.InitializingService;
import com.jy.oms.framework.util.AopTargetUtils;
import com.jy.oms.framework.util.NetworkUtil;
import com.jy.oms.framework.util.SpringUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RMap;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 在容器加载完后启动task，优先级最高先执行
 *
 * @author liuquan
 */
@Service
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExecutorStarterListener implements InitializingService {
    private Logger logger = LoggerFactory.getLogger(ExecutorStarterListener.class);
    @Autowired
    private ITaskHandlerManager taskHandlerManager;
    @Autowired
    private ITaskController taskController;
    @Autowired
    private IRegistryService registryService;
    @Autowired
    private List<ITaskHandlerProcessor> taskHandlerProcessors;

    @Override
    public void initService(ApplicationContext applicationContext) {
        this.checkGetExecutorConfig(applicationContext);
        ExecutorConfig executorConfig = ExecutorContext.getExecutorConfig();
        if (executorConfig == null) {
            return;
        }

        //获取RedissonClient对象
        this.parseRedissonClient(executorConfig);
        //从全局视角校验任务配置是否合法
        this.checkGlobalExecutorConfig(executorConfig);
        //异步任务初始化
        this.startExecuteTask(executorConfig);
        //job初始化
        this.startExecuteStandaloneJob(applicationContext, executorConfig);
        //注册节点
        this.registExecutorServer(executorConfig);

        logger.info("异步任务初始化完成......");
    }

    private void checkGetExecutorConfig(ApplicationContext applicationContext) {
        ExecutorConfig executorConfig = null;
        try {
            executorConfig = applicationContext.getBean(ExecutorConfig.class);
        } catch (BeansException e) {
        }

        if (executorConfig == null) {
            return;
        }

        ExecutorConfig copyExecutorConfig = ExecutorContext.init(executorConfig);
        String businessGroup = copyExecutorConfig.getBusinessGroup();
        if (StringUtils.isBlank(businessGroup)) {
            throw new TaskConfigException("ExecutorConfig属性businessGroup不能为空.");
        } else {
            copyExecutorConfig.setBusinessGroup(businessGroup.toUpperCase());
        }

        if (StringUtils.isBlank(copyExecutorConfig.getEnv())) {
            if (!SystemUtil.getOsInfo().isLinux()) {
                copyExecutorConfig.setEnv(NetworkUtil.getLocalhostStr());
            } else {
                copyExecutorConfig.setEnv(ServerConfigAdapter.getEnv());
            }
        }
        copyExecutorConfig.setEnv(copyExecutorConfig.getEnv().toUpperCase());

        String redisPrefix = copyExecutorConfig.getBusinessGroupRedisPrefix();
        if (StringUtils.isBlank(redisPrefix)) {
            copyExecutorConfig.setBusinessGroupRedisPrefix(CacheConstants.DEFAULT_CACHE_PREFIX);
        }

        if (StringUtils.isBlank(copyExecutorConfig.getSign())) {
            copyExecutorConfig.setSign(copyExecutorConfig.getBusinessGroup());
        }

        ExecutorHandlerParser executorHandlerParser = applicationContext.getBean(ExecutorHandlerParser.class);
        try {
            executorHandlerParser.parse();
        } catch (Exception e) {
            throw new TaskConfigException(e);
        }
    }

    /**
     * 从全局视角校验任务配置是否合法
     */
    private void checkGlobalExecutorConfig(ExecutorConfig executorConfig) {
        if(ExecutorContext.isDev()){
            return;
        }
        
        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        String signKey = CacheConstants.genFrameworkKey("sign", executorConfig.getSign());
        RSet<String> set = redissonClient.getSet(signKey);
        //现在只校验 提交任务|执行任务 缓存前缀应用配置是否一致
        set.add(executorConfig.getBusinessGroupRedisPrefix());
        int size = set.size();
        if (size > 1) {
            throw new TaskConfigException("存在不一致的缓存前缀配置，请检查ExecutorConfig.businessGroupRedisPrefix属性");
        }
        set.expire(1, TimeUnit.DAYS);
    }

    /**
     * 获取RedissonClient原始对象；
     * 由于框架在RedissonClient对象上定义了切面[RedissonClientAspect]，key自动加app.name；
     * 异步任务框架缓存key以 【缓存前缀:业务组标识】 开头；
     */
    private void parseRedissonClient(ExecutorConfig executorConfig) {
        RedissonClient redissonClient;
        try {
            RedissonClient redissonClientProxy = SpringUtil.getBean(executorConfig.getRedissonClientBean(), RedissonClient.class);
            Object proxy = AopTargetUtils.getTarget(redissonClientProxy);
            if (proxy instanceof RedissonClient) {
                redissonClient = (RedissonClient) proxy;
            } else {
                Field field = proxy.getClass().getDeclaredField("target");
                field.setAccessible(true);
                redissonClient = (RedissonClient) field.get(proxy);
            }
        } catch (Exception e) {
            throw new TaskConfigException("获取RedissonClient代理对象报错, beanName:" + executorConfig.getRedissonClientBean(), e);
        }

        if (redissonClient == null) {
            throw new TaskConfigException("获取RedissonClient代理对象报错, beanName:" + executorConfig.getRedissonClientBean());
        }

        RedissonClientProxy.setRedissonClient(redissonClient);
    }

    private void startExecuteTask(ExecutorConfig executorConfig) {
        if (!executorConfig.isEnableTaskExecutor()) {
            return;
        }

        Map<TaskGroup, List<TaskHandlerWrapper>> taskHandlerMap = taskHandlerManager.loadAllExecutableTaskHandler();
        if (MapUtils.isEmpty(taskHandlerMap)) {
            return;
        }

        //任务调度器初始化
        for (Map.Entry<TaskGroup, List<TaskHandlerWrapper>> entry : taskHandlerMap.entrySet()) {
            taskController.init(entry.getKey());
        }

        //task执行校验器初始化
        TaskExecutorChainChecker.getInstance().init();

        //任务初始化完成后置处理
        //优先级排序，优先级高的先执行校验
        taskHandlerProcessors.sort(Comparator.comparing(ITaskHandlerProcessor::getProcessorOrder));
        taskHandlerProcessors.stream().forEach(ITaskHandlerProcessor::processAfterTaskHandlerInitialization);

        //多节点情况下，需注册
        if (executorConfig.isEnableCluster()) {
            registryService.registryWorkNode();
        }

        //开始任务调度
        for (Map.Entry<TaskGroup, List<TaskHandlerWrapper>> entry : taskHandlerMap.entrySet()) {
            taskController.schedule(entry.getKey());
        }
    }

    private void startExecuteStandaloneJob(ApplicationContext applicationContext, ExecutorConfig executorConfig) {
        Map<String, IStandaloneJob> beans = applicationContext.getBeansOfType(IStandaloneJob.class);
        if (MapUtils.isEmpty(beans)) {
            return;
        }

        boolean enableJob;
        if (SystemUtil.getOsInfo().isLinux()) {
            enableJob = true;
            executorConfig.setStandaloneJobConfig(StandaloneJobConfig.create().setEnableJob(true));
        } else {
            StandaloneJobConfig standaloneJobConfig = executorConfig.getStandaloneJobConfig();
            if (standaloneJobConfig == null) {
                enableJob = true;
                executorConfig.setStandaloneJobConfig(StandaloneJobConfig.create().setEnableJob(enableJob));
            } else {
                enableJob = standaloneJobConfig.isEnableJob();
            }
        }

        if (enableJob) {
            //workerServer心跳线程启动
            WorkerServerThreadManager.getInstance().startWorkerServerThread();
        }
    }

    private void registExecutorServer(ExecutorConfig executorConfig){
        if(!executorConfig.isEnableTaskExecutor()){
            return;
        }

        if(ExecutorContext.isDev()){
            return;
        }

        RedissonClient redissonClient = RedissonClientProxy.getRedissonClient();
        String cacheKey = CacheConstants.genFrameworkKey(CacheConstants.EXECUTOR_SERVER_REGIST);
        RMap<String, String> map = redissonClient.getMap(cacheKey);
        map.put(executorConfig.getBusinessGroup(), NetworkUtil.getLocalhostStr() + ":" + getTomcatPort());
    }

    private int getTomcatPort() {
        try {
            MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
            Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
            String port = objectNames.iterator().next().getKeyProperty("port");

            return Integer.valueOf(port);
        } catch (Exception e) {
            return 80;
        }
    }
}
